<template>
  <backContainer>
    <card :width="1200" height="calc(100vh - 68px - 18px - 30px)" :top="24">
      <approvalComponent
        :stuEvaluateList="stuEvaluateList"
        :copyGradeEntityList="copyGradeEntityList"
        @approvalAnswer="approvalAnswer"
        :loading="loading"
        :examInfo="examInfo"
        :approvalType="approvalType"
        :msgInfo="msgInfo"
        :needNext="needNext"
        :examUseTime="examUseTime"
        :paperType="paperType"
      ></approvalComponent>
    </card>
  </backContainer>
</template>

<script>
import approvalComponent from './components/approvalComponent'
import { updatePost_readmessage } from '@/api/home/message'
import {
  approvalAnswerApi,
  getExamPaperForGradeApi,
  getGroupMemberListApi,
  getNextExamPaperForGroupApi
} from '@/api/ExaminationModule/approval'
import { calculateElapsedTime } from './formatTreeData'
import { returnName, returnType } from '@/utils/util'

export default {
  name: 'approvalAnswer',
  components: {
    approvalComponent
  },
  data() {
    return {
      approvalType: '',
      paperType: 1,
      keyId: null,
      stuEvaluateList: [],
      copyGradeEntityList: [],
      objectiveTypes: [4, 5],
      examInfo: {},
      examUseTime: '',
      needNext: '',

      msgInfo: {
        studentInfo: '--',
        taskInfo: '--',
        groupName: '--'
      },
      loading: false
    }
  },
  watch: {
    '$route.query.keyId': {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.keyId = val - 0
            this.getExaminationAnswerList()
          })
        }
      },
      immediate: true
    }
  },
  created() {
    this.needNext = this.$route.query.needNext
    this.approvalType = this.$route.query.approvalType
  },
  mounted() {

  },
  methods: {
    async approvalAnswer(arr) {
      const loading = this.$loading({
        lock: true,
        text: '正在提交',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await approvalAnswerApi(arr)
        if (res.code == 200) {
          this.$modal.msgSuccess('提交成功！')
          this.$router.go(-1)
        }
      } catch (error) {
        console.log(error)
      } finally {
        loading.close()
      }
    },
    //获取组内成员列表
    async getGroupMemberList() {
      let res = await getGroupMemberListApi(this.keyId)
      const { code, data } = res
      if (code == 200) {
        let arr = []
        for (const groupMemberListElement of data.groupMemberList) {
          groupMemberListElement.scoreGot = undefined
          groupMemberListElement.teacherRemark = ''
          arr.push(groupMemberListElement)
        }
        return arr
      }
    },
    async getExaminationAnswerList() {
      this.loading = true
      let res
      try {
        let params = {
          type: this.approvalType
        }
        if (this.approvalType == 4) {
          params.leaderId = this.$route.query.leaderId
        }
        if (this.approvalType == 4) {
          // 如果是消息过来 就是获取的别人的卷子
          if (this.$route.query.from == 'msg') {
            res = await getExamPaperForGradeApi(this.keyId, params)
          } else {
            // 如果是学生 目录组间互评进来就调用下一份卷子
            let next = await getNextExamPaperForGroupApi(this.keyId, params)
            res = next.data
          }
        } else {
          res = await getExamPaperForGradeApi(this.keyId, params)
        }
        let resData = res.data
        this.paperType = resData.ccExamPaper.examType
        const source = this.$route.query.type === 'next' ? this.$route.query : resData
        this.msgInfo = {
          studentInfo: source.studentInfo,
          taskInfo: source.taskInfo,
          groupName: source.groupName
        }
        let examArr = resData.ccExamPaper.examPaperTitleList
        examArr.forEach(item => {
          item.showBigTitleIds = []
          item.topicList.forEach((topicItem) => {
            if (this.objectiveTypes.includes(topicItem.topicType)) {
              item.showBigTitleIds.push(topicItem.id)
            }
          })
        })
        //处理评价维度  数组数据
        let evaluateCategoryList = JSON.parse(JSON.stringify(resData.ccExamPaper.evaluateGradeEntityList));
        if (evaluateCategoryList && evaluateCategoryList.length > 0) {
          let stuEvaluateList = evaluateCategoryList[0].ccExamEvaluateCategoryEntityList;
          this.stuEvaluateList = stuEvaluateList;
          this.copyGradeEntityList = evaluateCategoryList;
          evaluateCategoryList.forEach((evaluateItem)=>{
            if (evaluateItem.ccExamEvaluateCategoryEntityList){
              evaluateItem.ccExamEvaluateCategoryEntityList.forEach((item)=>{
                if (item.ccExamEvaluateParamEntityList){
                  item.ccExamEvaluateParamEntityList.forEach((paramItem)=>{
                    if (!paramItem.score && paramItem.score!=0){
                      paramItem.score = undefined
                    }
                  })
                }
              })
            }
          })
        }
        let groupMemberList = []
        if (resData.ccExamPaper.groupId) {
          groupMemberList = await this.getGroupMemberList()
        }
        let formatObj = {
          ...resData,
          examPaperTitleList: examArr,
          groupMemberList: groupMemberList
        }
        let data = this.formatDataInfo(formatObj)
        console.log('data>>>>>>>>>>>', data)
        this.examInfo = data
        this.examUseTime = calculateElapsedTime(resData.ccExamPaper.startTime, resData.ccExamPaper.finishTime)
        //需要清除已读消息
        if (this.$route.query.readMessageId && [1, -1].includes(formatObj.passing)) {
          this.updateReadmessage(this.$route.query.readMessageId)
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    //格式化数据
    formatDataInfo(examInfo) {
      const { groupId } = examInfo.ccExamPaper
      const groupMemberList = examInfo.groupMemberList
      const examArr = examInfo.examPaperTitleList

      // 处理单个题目项
      const processTopicItem = (topic, groupMembers) => {
        const isChoiceType = [0, 1].includes(topic.topicType)
        const hasAnswer = !!topic.topicAnswer
        const result = {
          ...topic,
          groupMemberList: JSON.parse(JSON.stringify(groupMembers)),
          userAnswer: '',
          multiAnswers: [],
          echoFile: [],
          settlePic: topic.settlePic ? topic.settlePic.split(',') : [],
          previewList: []
        }

        // 处理选项选中状态
        if (isChoiceType) {
          result.topicOptionList = topic.topicOptionList.map(item => ({
            ...item,
            isChecked: hasAnswer
              ? (topic.topicAnswer.answer === item.label ||
                (topic.topicAnswer.multiAnswers || []).includes(item.label))
              : false
          }))
        }

        // 处理已有答案的情况
        if (hasAnswer) {
          result.userAnswer = topic.topicAnswer.answer || ''
          result.multiAnswers = topic.topicAnswer.multiAnswers || []

          // 处理文件信息
          if (topic.topicAnswer.fileInfo) {
            const fileInfoArr = JSON.parse(topic.topicAnswer.fileInfo)
            result.echoFile = fileInfoArr.map(file => ({
              ...file,
              type: file.url ? returnType(file.url) : undefined,
              name: file.name ? file.name : file.url ? returnName(file.url) : undefined
            }))

            // 构建预览列表
            result.previewList = result.echoFile.filter(file => file.type === 1).map(file => file.url)
          }
        }

        // 处理得分信息
        const scoreEntity = topic.ccExamPaperTopicScoreEntityList[0]
        if ((groupId && topic.scoreType === 0) || !groupId) {
          result.scoreGot = scoreEntity ? scoreEntity.scoreGot : undefined
          result.teacherRemark = scoreEntity ? scoreEntity.teacherRemark : ''
        }

        // 处理小组独立给分模式
        if (topic.ccExamPaperTopicScoreEntityList.length > 0 && groupId && topic.scoreType === 1) {
          result.groupMemberList = topic.ccExamPaperTopicScoreEntityList.map(item => ({
            ...item
          }))
        }

        // 处理客观题对错判断
        if (topic.topicType < 4 && scoreEntity) {
          result.right = scoreEntity.right
          result.scoreGot = scoreEntity.scoreGot
        }

        return result
      }

      // 处理大题
      const formatArr = examArr.map(examItem => ({
        ...examItem,
        topicList: examItem.topicList.map(topic =>
          processTopicItem(topic, groupMemberList)
        )
      }))

      // 返回格式化后的对象
      return {
        ...examInfo,
        totalScore: examInfo.ccExamPaper.totalScore,
        passingGrade: examInfo.ccExamPaper.passingGrade,
        groupId,
        examPaperTitleList: formatArr
      }
    },
    async updateReadmessage(id) {
      //更新消息状态
      let res = await updatePost_readmessage(id)
      console.log('更新消息状态', res)
    }
  }
}
</script>

<style scoped lang="scss">

</style>
